package com.gobang.common.handler;

import com.gobang.service.ConnectionManagerService;
import com.gobang.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;

/**
 * 自定义WebSocket处理器
 * 处理WebSocket连接的建立和断开事件
 * 
 * @author System
 * @since 1.0.0
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class CustomWebSocketHandler {
    
    private final ConnectionManagerService connectionManagerService;
    private final UserService userService;
    
    /**
     * 处理WebSocket连接建立事件
     *
     * @param event 连接建立事件
     */
    @EventListener // 监听Spring WebSocket事件
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        // 到这里，其实已经握手成功了，触发对应的事件进入该方法
        try {
            // 获取 Stomp 消息头信息
            StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
            String sessionId = headerAccessor.getSessionId();
            Principal user = headerAccessor.getUser();
            
            if (user != null && sessionId != null) {
                Long userId = Long.parseLong(user.getName());
                
                // 获取用户信息
                var userInfo = userService.getUserById(userId);
                String username = userInfo != null ? userInfo.getUsername() : "Unknown";
                Integer currentScore = userInfo != null ? userInfo.getCurrentScore() : 0;
                
                // 添加连接到管理器
                connectionManagerService.addConnection(userId, sessionId, username, currentScore);
                
                log.info("WebSocket连接建立：sessionId={}, userId={}, username={}", 
                        sessionId, userId, username);
            } else {
                log.warn("WebSocket连接建立失败，缺少用户信息或会话ID");
            }
        } catch (Exception e) {
            log.error("处理WebSocket连接建立事件异常", e);
        }
    }
    
    /**
     * 处理WebSocket连接断开事件
     *
     * @param event 连接断开事件
     */
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        try {
            StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
            String sessionId = headerAccessor.getSessionId();
            
            if (sessionId != null) {
                // 根据会话ID获取用户ID
                Long userId = connectionManagerService.getUserIdBySession(sessionId);
                
                // 移除连接
                connectionManagerService.removeConnectionBySession(sessionId);
                
                log.info("WebSocket连接断开：sessionId={}, userId={}", sessionId, userId);
            } else {
                log.warn("WebSocket连接断开处理失败，缺少会话ID");
            }
        } catch (Exception e) {
            log.error("处理WebSocket连接断开事件异常", e);
        }
    }
}